
package com.hlkj.pay.app.merchant.ext.impl.huifu.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.HuiFuExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.huifu.HuiFuScenePayOrderExtPt;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuConfig;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuMerchantAccessCompanyParamsHandle;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuPayOrderRequestParamsHandler;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuPayOrderResponseParamsHandler;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.vo.order.req.PayOrderCommonParamReq;
import com.huifu.bspay.sdk.opps.client.BasePayClient;
import com.huifu.bspay.sdk.opps.core.BasePay;
import com.huifu.bspay.sdk.opps.core.config.MerConfig;
import com.huifu.bspay.sdk.opps.core.net.BasePayRequest;
import com.huifu.bspay.sdk.opps.core.request.V2TradePaymentJspayRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/10/11 16:22
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = HuiFuExtConstant.JSAPI)
public class HuiFuJsapiPayOrderExtPt extends HuiFuSceneCommonPayOrder implements HuiFuScenePayOrderExtPt {

    @Override
    public void submitChannelPayOrder(ChannelPayOrderContext channelPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        HuiFuConfig huiFuConfig = JsonUtils.parseObject(channelConfig, HuiFuConfig.class);
        HuiFuAppChannelParams huiFuAppChannelParams = JsonUtils.parseObject(channelPayOrderContext.getMerchantAppChannelDO().getAppConfigJson(), HuiFuAppChannelParams.class);
        try {
            // 额外参数信息
            PayOrderCommonParamReq.Extra extra = channelPayOrderContext.getExtra();
            PayWayDO payWayDO = channelPayOrderContext.getPayWayDO();

            if (extra == null) {
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                channelPayOrderContext.setRemark("斗拱提交JSAPI 支付 扩展参数不能为空");
                return;
            }
            if (payWayDO.getType() == 1 && !StringUtils.hasText(extra.getSubAppid())) {
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                channelPayOrderContext.setRemark("斗拱微信提交JSAPI支付 appid不能为空");
                return;
            }
            if (!StringUtils.hasText(extra.getUserId())) {
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                channelPayOrderContext.setRemark("斗拱提交JSAPI 支付 userId不能为空");
                return;
            }

            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            V2TradePaymentJspayRequest request = HuiFuPayOrderRequestParamsHandler.v2TradePaymentJspayRequest(channelPayOrderContext);
            // 汇付客户Id
            request.setHuifuId(huiFuAppChannelParams.getHuiFuId());
            log.info("斗拱提交正扫支付订单请求信息response:{}", JsonUtils.toJsonString(request));
            // 3. 发起API调用
            Map<String, Object> response = BasePayClient.request(request, false);
            log.info("斗拱提交正扫支付订单返回信息response:{}", JsonUtils.toJsonString(response));
            HuiFuPayOrderResponseParamsHandler.processSubmitOrderResultData(response, channelPayOrderContext);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("支付提交正扫支付订单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderContext.setRemark("斗拱提交正扫支付订单请求失败,失败信息" + e.getMessage());
            channelPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    @Override
    public void queryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void closeChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonCloseChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void queryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelClosePayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void refundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public void queryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonQueryRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    public static void main(String[] args) throws Exception {
        // 汇付分配的产品号
        String DEMO_PRODUCT_ID = "MYPAY";
        // 汇付分配的系统号
        String DEMO_SYS_ID = "6666000103334211";
        // 服务商私钥，用于调用接口时进行签名
        String DEMO_RSA_PRIVATE_KEY = "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQCcq0k6c3+q/7dYlRimvSnLFgL6ab67zECrho9zYRkeSiPZXFMHr9MsfLqbrJa3a9nxTqFi6fiNnqAAt+OxuaX9R7cmgH5gwFeGkK1KjwQy2jZX7f7d+0EdifiLpKVOx9IM1v9q4tXt8dHess421aKHpOuoBviFs7GLHV5qCmihD0Zv/HJ4B1dORLZCRM8fhKqCg1vT3mKmM+IiYJeuB7IYhtrWLTH/bTzvCkPWl0w+emvx1N577csTs5vVzOzB6o0k1ndMc7d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Bw58OwfgX26ep2dVYgJZ3e6UdshKedizPsqCj3gIaUpPH5R5uMh4FzUCgYEAleGIQh+k2GhTtg1ZK71B7vTZo54a+4PfoRFJbmLBGAKKbKy9YT1lOwYY5fzucYQ0QZWdVuI3w5U4n96hkYTYD051pgQn7GQZp7RZQbm+IzSJ2TFDgDHynMzl4OsIcTT6QN8T0qsQm57k4/XUz3+hGA8G6oOaupITau3pFXOhieo=";
        // 汇付公钥，用于对汇付返回报文进行签名验证
        String DEMO_RSA_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlfkjf2F4xsEsWFwVAjjOoqhEh6u0dMl2Z1xsTL/ytzyGRaMRXJUr47zdwpI6+3OZE+IlJwECp8T0jdFzml5vP8TWENQ4OMFt7aZ1Z/F7F9lpvMAQ+4WvucQ5ypRoLG/md0ZGnYOTb4Vnc8Pc3/fsd5UxD/nzOu5Lf4XU04FG1M0kYyjr4K";
        // 1. 数据初始化，填入对应的商户配置
        BasePay.prodMode = BasePay.MODE_INNER_TEST;
        MerConfig merConfig = new MerConfig();
        merConfig.setProcutId(DEMO_PRODUCT_ID);
        merConfig.setSysId(DEMO_SYS_ID);
        merConfig.setRsaPrivateKey(DEMO_RSA_PRIVATE_KEY);
        merConfig.setRsaPublicKey(DEMO_RSA_PUBLIC_KEY);
        BasePay.initWithMerConfig(merConfig);
        // 2.组装请求参数
        Map<String, Object> paramsInfo = new HashMap<>();
        // 请求日期
        paramsInfo.put("req_date", "20250627");
        // 请求流水号
        paramsInfo.put("req_seq_id", "T20250627235555002211");
        // 商户号
        paramsInfo.put("huifu_id", "6666000103334211");
        // 商品描述
        paramsInfo.put("goods_desc", "测试订单");
        // 交易类型
        paramsInfo.put("trade_type", "A_NATIVE");
        // 交易金额
        paramsInfo.put("trans_amt", "0.01");
        // 交易有效期
        paramsInfo.put("time_expire", "20250627165959");
        //支付宝参数集合
        Map<String, Object> alipay_data = new HashMap<>();
        alipay_data.put("subject", "测试订单");
        paramsInfo.put("alipay_data", alipay_data);
        // 异步通知地址
        paramsInfo.put("notify_url", "https://test-api.hbhlpay.com/applyments.ffpay/test");
        // 3. 发起API调用
        Map<String, Object> response = BasePayRequest.requestBasePay("v3/trade/payment/jspay", paramsInfo, null, false);;
        System.out.println(response);
    }
}
